package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.*;

import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
public class SaleOrderFaHuoRunnable implements Exe {


    private Connection connection;

    public SaleOrderFaHuoRunnable(Connection connection) {
        this.connection = connection;
    }

    public static final ThreadLocal<List<Integer>> FAHUO_IDS = new ThreadLocal<>();

    @Override
    public boolean execute(int count) {
        //拿到生成的销售订单明细
        List<Integer> orderIds = GEN_ORDER_IDS.get();
        if (CollectionUtil.isEmpty(orderIds)) return Boolean.FALSE;

        List<Integer> fahuoIds = new ArrayList<>();

        int fahuoMaxId = getMaxId(connection, "xs05SalesAndDispatch");
        int ckdId = getMaxId(connection, "lists");
        for (int i = 1; i <= orderIds.size(); i++) {
            int curId = fahuoMaxId + i;
            // 唯一发货单号生成
            String fahuodanhao = GenUtil.getNoFromTable(connection, "XSFH", "xs05SalesAndDispatch", "shipmentOrderNumber");
            //查询销售订单
            Map<String, Object> saleOrder = DbUtil.getById(connection, "salesOrders", orderIds.get(i - 1));
            //查询销售订单明细
            List<LinkedHashMap<String, Object>> details;
            try {
                PreparedStatement statement = connection.prepareStatement("select * from xs02SalesOrderBreakdown where  associatedSalesOrders = ?");
                statement.setInt(1, orderIds.get(i - 1));
                ResultSet resultSet = statement.executeQuery();
                details = DbUtil.resultSetToList(resultSet);

                int finalI = i;
                List<LinkedHashMap<String, Object>> associatedSalesOrders = details.stream().filter(cur -> cur.get("associatedSalesOrders").equals(orderIds.get(finalI - 1))).toList();

                int maxId = getMaxId(connection, "xssalesDispatchDetails");
                for (int j = 1; j <= associatedSalesOrders.size(); j++) {
                    //创建发货单详情
                    int detailId = maxId + j;
                    PreparedStatement statement1 = connection.prepareStatement("insert into xssalesDispatchDetails (id,associatedConsignmentOrder,productInformation,quantityOfShipments,amountOfShipment,unitPriceForShipment,numberOfOrders,numberOfRemainingShipments,numberOfRefunds,amountOfReturn,synchronisingFolderFailedSS,modifyer) " +
                            "values (?,?,?,?,?,?,?,?,?,?,?,?)");
                    statement1.setInt(1, detailId);
                    statement1.setInt(2, curId);
                    statement1.setInt(3, Integer.parseInt(associatedSalesOrders.get(j - 1).get("productInformation").toString()));
                    statement1.setBigDecimal(4, new BigDecimal(associatedSalesOrders.get(j - 1).get("quantityOfShipments").toString()));
                    statement1.setBigDecimal(5, new BigDecimal(new BigDecimal(associatedSalesOrders.get(j - 1).get("unitPrice").toString()).multiply(new BigDecimal(associatedSalesOrders.get(j - 1).get("quantityOfShipments").toString())).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
                    statement1.setBigDecimal(6, new BigDecimal(associatedSalesOrders.get(j - 1).get("unitPrice").toString()));
                    statement1.setBigDecimal(7, new BigDecimal(associatedSalesOrders.get(j - 1).get("quantityOfShipments").toString()));
                    statement1.setBigDecimal(8, BigDecimal.ZERO);
                    statement1.setBigDecimal(9, BigDecimal.ZERO);
                    statement1.setBigDecimal(10, BigDecimal.ZERO);
                    statement1.setString(11, saleOrder.get("synchronisingFolderFailedSS").toString());
                    statement1.setString(12, saleOrder.get("synchronisingFolderFailedSS").toString());

                    statement1.execute();
                }
                //创建发货单
                PreparedStatement statement2 = connection.prepareStatement("insert into xs05SalesAndDispatch (id,shipmentOrderNumber,dateOfShipment,shipper,associatedSalesOrders,clientInformation,quantityOfShipments,synchronisingFolderFailedSS,created,approvalStatus) values (?,?,?,?,?,?,?,?,?,?)");
                statement2.setInt(1, curId);
                statement2.setString(2, fahuodanhao);
                statement2.setTimestamp(3, GenUtil.CUR_TIME_STAMP.get());
                statement2.setString(4, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement2.setInt(5, orderIds.get(i - 1));
                statement2.setInt(6, Integer.parseInt(saleOrder.get("clientInformation").toString()));
                statement2.setBigDecimal(7, new BigDecimal(saleOrder.get("numberOfOrders").toString()));
                statement2.setString(8, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement2.setTimestamp(9, GenUtil.CUR_TIME_STAMP.get());
                statement2.setString(10, "已通过");

                statement2.execute();

                //创建出库明细
                int ckmxId = getMaxId(connection, "ck02CheckoutFormCheckout");
                int curCkdId = ckdId + i;

                for (int j = 1; j <= associatedSalesOrders.size(); j++) {
                    PreparedStatement preparedStatement = connection.prepareStatement("insert into ck02CheckoutFormCheckout(id,productInformation,numberOfReleases,inventoryUnitPrice,numberOfDeposits,linkOutList,synchronisingFolderFailedSS,modifyer,created,modified) values (?,?,?,?,?,?,?,?,?,?)");
                    preparedStatement.setInt(1, ++ckmxId);
                    preparedStatement.setInt(2, Integer.parseInt(associatedSalesOrders.get(j - 1).get("productInformation").toString()));
                    preparedStatement.setBigDecimal(3, new BigDecimal(associatedSalesOrders.get(j - 1).get("quantityOfShipments").toString()));
                    preparedStatement.setBigDecimal(4, new BigDecimal(associatedSalesOrders.get(j - 1).get("unitPrice").toString()));
                    preparedStatement.setBigDecimal(5, new BigDecimal(new BigDecimal(associatedSalesOrders.get(j - 1).get("unitPrice").toString()).multiply(new BigDecimal(associatedSalesOrders.get(j - 1).get("quantityOfShipments").toString())).toString()));
                    preparedStatement.setInt(6, curCkdId);
                    preparedStatement.setString(7, saleOrder.get("synchronisingFolderFailedSS").toString());
                    preparedStatement.setString(8, saleOrder.get("synchronisingFolderFailedSS").toString());
                    preparedStatement.setTimestamp(9, GenUtil.CUR_TIME_STAMP.get());
                    preparedStatement.setTimestamp(10, GenUtil.CUR_TIME_STAMP.get());
                    preparedStatement.execute();

                }
                //创建出库单
                PreparedStatement statement3 = connection.prepareStatement("insert into lists (id,cashiersNumber,poolType,collectionDate,operator,synchronisingFolderFailedSS,created,associatedOrders,clientInformation) values (?,?,?,?,?,?,?,?,?)");
                statement3.setInt(1, curCkdId);
                statement3.setString(2, GenUtil.getNoFromTable(connection, "CK", "lists", "cashiersNumber"));
                statement3.setString(3, "销售出库");
                statement3.setTimestamp(4, GenUtil.CUR_TIME_STAMP.get());
                statement3.setString(5, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement3.setString(6, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement3.setTimestamp(7, GenUtil.CUR_TIME_STAMP.get());
                statement3.setInt(8, orderIds.get(i - 1));
                statement3.setInt(9, Integer.parseInt(saleOrder.get("clientInformation").toString()));
                statement3.execute();
                fahuoIds.add(curId);

            } catch (Exception e) {
                throw new RuntimeException("数据生成失败",e);
            }
        }

        FAHUO_IDS.set(fahuoIds);
        return Boolean.TRUE;
    }
}
